<?php

declare(strict_types=1);

namespace App\Fastapp\Job;

use App\Fastapp\Model\Account;
use App\Fastapp\Model\AccountWallet;
use Hyperf\AsyncQueue\Job;

class WalletAddJob extends Job
{
    public function __construct(public int $user_id, public int $account_type, public string $symbol)
    {
    }

    public function handle(): void
    {
        try {
            if ($this->user_id) {
                $app_setting = api_cache()->getAppSetting($this->account_type);
                if (!$app_setting || empty($app_setting['symbol'])) return;
                $app_symbols = explode(',', $app_setting['symbol']);
                if ($this->symbol) $symbols = explode(',', $this->symbol);
                else $symbols = $app_symbols;
                $register_demo_balance = $app_setting['register_demo_balance'] ?? 0;
                $in = [];
                $channel = get_user_cache('channel', $this->user_id) ?: 1;
                foreach ($symbols as $symbol) {
                    if ($symbol != $app_symbols[0]) $register_demo_balance = 0;
                    $in[] = [
                        'user_id' => $this->user_id,
                        'currency_id' => get_currency_cache($symbol)['id'],
                        'symbol' => $symbol,
                        'channel' => $channel,
                        'balance_demo' => $register_demo_balance,
                    ];
                }
                if (AccountWallet::query()->insert($in)) fastapp_queue_push(new WalletAddressJob($this->user_id, $this->symbol));
            } else {
                Account::query()->select(['gene_id'])->where(['type' => $this->account_type])->chunk(1, function ($chunk) {
                    foreach ($chunk as $item) fastapp_queue_push(new WalletAddJob($item->gene_id, $this->account_type, $this->symbol));
                });
            }
        } catch (\Throwable $throwable) {
            sys_notify($throwable->getMessage() . '|' . $throwable->getTraceAsString());
        }
    }
}
